/*
RetroLeague - Mobile application for The Retro League Podcast
Copyright (C) 2010-2013 Hugues Johnson

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software 
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

package com.huguesjohnson.retroleague.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public abstract class HttpFetch{
	//see - http://stackoverflow.com/questions/4414839/bitmapfactory-decodestream-returns-null-without-exception
	public static InputStream fetch(String address,int timeout) throws MalformedURLException,IOException{
	    HttpGet httpRequest=new HttpGet(URI.create(address));
	    HttpClient httpclient=new DefaultHttpClient();
	    final HttpParams httpParameters=httpclient.getParams();
	    HttpConnectionParams.setConnectionTimeout(httpParameters,timeout);
	    HttpConnectionParams.setSoTimeout(httpParameters,timeout);
	    HttpResponse response=(HttpResponse)httpclient.execute(httpRequest);
	    HttpEntity entity=response.getEntity();
	    BufferedHttpEntity bufHttpEntity=new BufferedHttpEntity(entity);
	    InputStream instream=bufHttpEntity.getContent();
	    return(instream);
	}
	
	public static Bitmap fetchBitmap(String imageAddress,int timeout) throws MalformedURLException,IOException{
		return(BitmapFactory.decodeStream(fetch(imageAddress,timeout)));
	}
}